'''
Created on 2011-05-11

@author: quermit
'''
import ldap
import logging

from PyQt4.QtCore import QThread


log = logging.getLogger(__name__)


class LDAPIndexReader(QThread):

    def __init__(self, parent, addr, path):
        super(LDAPIndexReader, self).__init__(parent)
        self.__addr = addr
        self.__path = path
        self.error = None
        self.result = []

    def run(self):
        conn = None
        try:
            conn = ldap.initialize(self.__addr)
            conn.bind_s('', '')
            log.info("Searching regions: %s ..." % self.__path)
            regions_raw = conn.search_s(self.__path, ldap.SCOPE_ONELEVEL, '(objectClass=country)')
            regions = []
            for region_raw in regions_raw:
                region = {'path': region_raw[0]}
                region['country'] = region_raw[1]['c'][0]
                region['description'] = region_raw[1]['description'][0]
                regions.append(region)

                log.info("Searching indexes: %s ..." % region['path'])
                indexes_raw = conn.search_s(region['path'], ldap.SCOPE_ONELEVEL, '(objectClass=account)')
                region['indexes'] = []
                for index_raw in indexes_raw:
                    index = {'path': index_raw[0]}
                    index['topic'] = index_raw[1]['uid'][0]
                    index.update(self.__parse_host(index_raw[1]['host'][0]))
                    index.update(self.__parse_desc(index_raw[1]['description'][0]))
                    region['indexes'].append(index)

            self.result = regions
        except ldap.LDAPError, e:
            log.error("LDAP Error: %s" % e)
            self.error = e
        finally:
            if conn:
                conn.unbind_s()

    def __parse_desc(self, desc):
        result = {}
        data = desc.split(':', 1)
        result['name'] = data[0]
        if len(data) > 1:
            result['description'] = data[1]
        return result

    def __parse_host(self, host):
        result = {}
        data = host.split(':')
        if len(data) < 3:
            log.error('Cannot parse host: %s' % host)
            return result
        result['host'] = data[0]
        result['port_queue'] = data[1]
        result['port_history'] = data[2]
        return result

